// pages/profile/profile.js
Page({
  data: {
    // 用户基本信息
    userInfo: {
      avatarUrl: '/assets/default-avatar.png',
      nickName: '单词达人',
      isLogin: false
    },
    
    // 学习总时长（分钟）
    totalStudyTime: 0,
    
    // 徽章列表
    badges: [
      {
        id: 1,
        name: '初学者',
        icon: 'badge-1',
        unlocked: true,
        condition: '完成首次单词学习（至少10个单词）',
        description: '欢迎加入单词训练营！迈出学习的第一步就值得表扬。'
      },
      {
        id: 2,
        name: '勤奋学习',
        icon: 'badge-2',
        unlocked: true,
        condition: '累计学习时长达到1小时（约60个单词）',
        description: '坚持学习一小时，证明你已经融入了学习节奏。'
      },
      {
        id: 3,
        name: '单词达人',
        icon: 'badge-3',
        unlocked: true,
        condition: '连续打卡5天',
        description: '连续五天的坚持，展现了你对学习的热情和决心。'
      },
      {
        id: 4,
        name: '记忆大师',
        icon: 'badge-4',
        unlocked: false,
        condition: '单日学习正确率达到90%以上（至少20个单词）',
        description: '超高的记忆力！你的大脑就像一台高效运转的计算机。'
      },
      {
        id: 5,
        name: '词汇王者',
        icon: 'badge-5',
        unlocked: false,
        condition: '累计掌握单词量达到500个',
        description: '词汇量的增长是最明显的进步，你已经掌握了大量单词！'
      },
      {
        id: 6,
        name: '英语专家',
        icon: 'badge-6',
        unlocked: false,
        condition: '完成一整本词书的学习（任意一本）',
        description: '征服了一整本词书！你的英语能力已经达到了一个新的高度。'
      }
    ],
    
    // 词书列表
    wordbooks: [
      {
        id: 1,
        name: '初一英语词汇',
        count: 800,
        selected: false
      },
      {
        id: 2,
        name: '初二英语词汇',
        count: 1200,
        selected: true
      },
      {
        id: 3,
        name: '初三英语词汇',
        count: 1500,
        selected: false
      }
    ],
    
    // 是否显示词书选择
    showWordbookSelector: false,
    
    // 当前选中的词书
    selectedWordbook: {
      name: '',
      count: 0
    },
    
    // 昵称编辑相关
    showNicknameModal: false,
    tempNickname: '',
    
    // 是否使用自定义信息
    useCustomProfile: false
  },
  
  onLoad: function() {
    // 检查用户是否已登录
    this.checkLoginStatus();
    
    // 获取当前选中的词书
    this.updateSelectedWordbook();
    
    // 加载用户资料
    this.loadUserProfile();
    
    // 加载学习时长
    this.loadStudyTime();
    
    // 加载徽章状态
    this.loadBadges();
    
    // 检查徽章状态
    this.checkBadges();
  },
  
  // 加载用户资料
  loadUserProfile: function() {
    // 从本地存储加载用户信息
    const userProfile = wx.getStorageSync('userProfile');
    if (userProfile) {
      this.setData({
        userInfo: {
          ...this.data.userInfo,
          ...userProfile,
          isLogin: true
        },
        useCustomProfile: userProfile.useCustomProfile || false
      });
    }
  },
  
  // 加载学习时长
  loadStudyTime: function() {
    // 从全局数据或本地存储获取学习时长
    const app = getApp();
    const studyData = app.globalData.studyData;
    
    // 获取每日学习记录
    const dailyProgress = wx.getStorageSync('dailyProgress') || {};
    let totalCompletedWords = 0;
    
    // 计算总学习单词量
    Object.values(dailyProgress).forEach(day => {
      totalCompletedWords += day.completed || 0;
    });
    
    // 假设每个单词学习平均需要1分钟
    const studyTimeMinutes = totalCompletedWords;
    
    // 设置学习时长
    this.setData({
      totalStudyTime: studyTimeMinutes
    });
  },
  
  // 更新当前选中的词书
  updateSelectedWordbook: function() {
    const selectedBook = this.data.wordbooks.find(book => book.selected) || {
      name: '未选择词书',
      count: 0
    };
    
    this.setData({
      selectedWordbook: {
        name: selectedBook.name,
        count: selectedBook.count
      }
    });
    
    // 同步到全局数据
    const app = getApp();
    app.globalData.currentWordbook = {
      id: selectedBook.id,
      name: selectedBook.name
    };
  },
  
  // 检查登录状态
  checkLoginStatus: function() {
    // 从本地存储检查用户信息
    const userProfile = wx.getStorageSync('userProfile');
    const isLogin = userProfile && (userProfile.avatarUrl !== '/assets/default-avatar.png');
    
    this.setData({
      'userInfo.isLogin': isLogin
    });
  },
  
  // 使用微信头像和昵称
  getUserWechatInfo: function(e) {
    if (e && e.detail && e.detail.userInfo) {
      const userInfo = {
        avatarUrl: e.detail.userInfo.avatarUrl,
        nickName: e.detail.userInfo.nickName,
        isLogin: true,
        useCustomProfile: false
      };
      
      this.setData({
        userInfo: {
          ...this.data.userInfo,
          ...userInfo
        },
        useCustomProfile: false
      });
      
      // 保存到本地存储
      wx.setStorageSync('userProfile', userInfo);
      
      wx.showToast({
        title: '已使用微信资料',
        icon: 'success'
      });
    }
  },
  
  // 使用自定义信息
  useCustomInfo: function() {
    this.setData({
      useCustomProfile: true,
      showNicknameModal: true,
      tempNickname: this.data.userInfo.nickName !== '单词达人' ? this.data.userInfo.nickName : ''
    });
  },
  
  // 选择头像
  onChooseAvatar: function(e) {
    const { avatarUrl } = e.detail;
    
    if (avatarUrl) {
      this.setData({
        'userInfo.avatarUrl': avatarUrl,
        'userInfo.isLogin': true,
        useCustomProfile: true
      });
      
      // 保存到本地存储
      const userProfile = wx.getStorageSync('userProfile') || {};
      wx.setStorageSync('userProfile', {
        ...userProfile,
        avatarUrl: avatarUrl,
        useCustomProfile: true
      });
      
      wx.showToast({
        title: '头像已更新',
        icon: 'success'
      });
    }
  },
  
  // 点击更换头像
  changeAvatar: function() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        this.setData({
          'userInfo.avatarUrl': tempFilePath,
          'userInfo.isLogin': true,
          useCustomProfile: true
        });
        
        // 保存到本地存储
        const userProfile = wx.getStorageSync('userProfile') || {};
        wx.setStorageSync('userProfile', {
          ...userProfile,
          avatarUrl: tempFilePath,
          useCustomProfile: true
        });
        
        wx.showToast({
          title: '头像已更新',
          icon: 'success'
        });
      }
    });
  },
  
  // 编辑昵称
  editNickname: function() {
    this.setData({
      showNicknameModal: true,
      tempNickname: this.data.userInfo.nickName
    });
  },
  
  // 昵称输入事件
  onNicknameInput: function(e) {
    this.setData({
      tempNickname: e.detail.value
    });
  },
  
  // 关闭昵称编辑弹窗
  closeNicknameModal: function() {
    this.setData({
      showNicknameModal: false
    });
  },
  
  // 保存昵称
  saveNickname: function() {
    if (!this.data.tempNickname.trim()) {
      wx.showToast({
        title: '昵称不能为空',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      'userInfo.nickName': this.data.tempNickname,
      'userInfo.isLogin': true,
      showNicknameModal: false,
      useCustomProfile: true
    });
    
    // 保存到本地存储
    const userProfile = wx.getStorageSync('userProfile') || {};
    wx.setStorageSync('userProfile', {
      ...userProfile,
      nickName: this.data.tempNickname,
      useCustomProfile: true
    });
    
    wx.showToast({
      title: '昵称已更新',
      icon: 'success'
    });
  },
  
  // 格式化学习时间
  formatStudyTime: function() {
    const minutes = this.data.totalStudyTime;
    if (minutes <= 0) {
      return '0小时';
    } else if (minutes < 60) {
      return `${minutes}分钟`;
    } else {
      const hours = Math.floor(minutes / 60);
      const remainMinutes = minutes % 60;
      return `${hours}小时${remainMinutes > 0 ? remainMinutes + '分钟' : ''}`;
    }
  },
  
  // 切换词书选择器显示状态
  toggleWordbookSelector: function() {
    this.setData({
      showWordbookSelector: !this.data.showWordbookSelector
    });
  },
  
  // 选择词书
  selectWordbook: function(e) {
    const { id } = e.currentTarget.dataset;
    
    // 更新选中状态
    const wordbooks = this.data.wordbooks.map(book => {
      return {
        ...book,
        selected: book.id === id
      };
    });
    
    this.setData({
      wordbooks,
      showWordbookSelector: false
    });
    
    // 更新当前选中的词书
    this.updateSelectedWordbook();
    
    // 提示用户
    wx.showToast({
      title: '词书切换成功',
      icon: 'success'
    });
  },
  
  // 跳转到系统设置
  gotoSettings: function() {
    wx.showToast({
      title: '设置功能开发中',
      icon: 'none'
    });
  },
  
  // 检查徽章状态，更新解锁情况
  checkBadges: function() {
    // 获取学习数据
    const app = getApp();
    const studyData = app.globalData.studyData || {
      totalWords: 0,
      masteredWords: 0,
      streakDays: 0,
      learningDays: 0
    };
    
    // 获取每日学习记录
    const dailyProgress = wx.getStorageSync('dailyProgress') || {};
    const dailyDetails = wx.getStorageSync('dailyDetails') || {};
    
    // 获取当前徽章状态
    const badges = [...this.data.badges];
    let isChanged = false;
    
    // 检查每个徽章的解锁条件
    // 徽章1：初学者 - 完成首次单词学习（至少10个单词）
    if (!badges[0].unlocked && studyData.totalWords >= 10) {
      badges[0].unlocked = true;
      isChanged = true;
    }
    
    // 徽章2：勤奋学习 - 累计学习时长达到1小时（约60个单词）
    if (!badges[1].unlocked && this.data.totalStudyTime >= 60) {
      badges[1].unlocked = true;
      isChanged = true;
    }
    
    // 徽章3：单词达人 - 连续打卡5天
    if (!badges[2].unlocked && studyData.streakDays >= 5) {
      badges[2].unlocked = true;
      isChanged = true;
    }
    
    // 徽章4：记忆大师 - 单日学习正确率达到90%以上（至少20个单词）
    // 遍历每日详情，检查是否有符合条件的记录
    let hasMastered = false;
    Object.keys(dailyDetails).forEach(date => {
      const detail = dailyDetails[date];
      if (detail && 
          detail.totalAnswered >= 20 && 
          detail.correctCount / detail.totalAnswered >= 0.9) {
        hasMastered = true;
      }
    });
    
    if (!badges[3].unlocked && hasMastered) {
      badges[3].unlocked = true;
      isChanged = true;
    }
    
    // 徽章5：词汇王者 - 累计掌握单词量达到500个
    if (!badges[4].unlocked && studyData.masteredWords >= 500) {
      badges[4].unlocked = true;
      isChanged = true;
    }
    
    // 徽章6：英语专家 - 完成一整本词书的学习
    // 获取当前选中的词书和完成情况
    const selectedBook = this.data.wordbooks.find(book => book.selected);
    
    // 计算这本词书已完成的单词数
    let completedWordsInBook = 0;
    Object.keys(dailyProgress).forEach(date => {
      completedWordsInBook += dailyProgress[date].completed || 0;
    });
    
    if (!badges[5].unlocked && 
        selectedBook && 
        completedWordsInBook >= selectedBook.count) {
      badges[5].unlocked = true;
      isChanged = true;
    }
    
    // 如有变化，更新徽章状态并保存
    if (isChanged) {
      this.setData({ badges });
      
      // 保存到本地存储
      wx.setStorageSync('userBadges', badges);
      
      // 显示新徽章解锁提示
      wx.showToast({
        title: '解锁了新徽章！',
        icon: 'success',
        duration: 2000
      });
    }
  },
  
  // 加载徽章状态
  loadBadges: function() {
    const savedBadges = wx.getStorageSync('userBadges');
    if (savedBadges && savedBadges.length) {
      this.setData({
        badges: savedBadges
      });
    }
  },
  
  // 查看徽章详情
  viewBadgeDetail: function(e) {
    const { id } = e.currentTarget.dataset;
    const badge = this.data.badges.find(item => item.id === id);
    
    if (!badge) return;
    
    let content = '';
    
    if (badge.unlocked) {
      content = `恭喜您已解锁此徽章！\n\n获取条件：${badge.condition}\n\n${badge.description}`;
    } else {
      content = `此徽章尚未解锁\n\n解锁条件：${badge.condition}`;
    }
    
    wx.showModal({
      title: badge.name,
      content: content,
      showCancel: false
    });
  }
}); 